'use strict';
const bcrypt = require('bcrypt');
module.exports = {
  // 加密密码
  genSaltPassword(password) {
    return new Promise((resolve,reject)=>{
      bcrypt.genSalt(10, function(err, salt) {
        bcrypt.hash(password, salt, function(err, hash) {
          if (!err){
            resolve(hash)
          }else{
            reject(err)
          }
        });
      });
    })
  },
  /**
   * @param{明文密码}_password
   * @param{hash密码}password
   */
   comparePassword(_password,password) {
    return new Promise((resolve,reject)=>{
      bcrypt.compare(_password, password, function(err, result) {
        if(!err){
          console.log(result);
           resolve(result)
        }else{
           reject(err)
        }
    })
  })
},
  // 创建token
   getToken(params){
     const {username,age} =params
     return  this.app.jwt.sign({ username,age }, this.app.config.jwt.secret,{expiresIn:'2s'});
   },
    // 验证token
    checkToken(token) {
        return this.app.jwt.verify(token, '123456')
    },
   //公共成功返回方法
  success(ctx,res=null){
     ctx.status=res.status?res.status:200
     if (res.status){
       delete res.status
     }
     ctx.body={
       ...res,
       data:res.data?res.data:null,
       msg:res.msg?res.msg:'请求成功',
       code:res.code?res.code:0,
     }
  },
    //分页数据处理
    getCurrent(data){
        function toInt(str) {
            if (typeof str === 'number') return str;
            if (!str) return str;
            return parseInt(str, 10) || 0;
        }
        const size=toInt(data.size)
        let current=toInt(data.current)
        if (current<=0){
            current=1
        }
        return{
            limit: size,
            offset: (current-1)*size,
        }
    },
    //获取当前时间
    getNowDate(){
       const date=new Date()
        const year=date.getFullYear()
        const month=date.getMonth()
        const day=date.getDate()
        return `${year}-${month}-${day}`
    }
}
